package com.highstockings.Task;

import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.ClassUtils;
import org.springframework.util.FileCopyUtils;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

/**
 * 在线cron表达式网站
 * http://cron.qqe2.com/
 * Created by diablo13064 on 2018/3/30.
 */
@Component
@Configurable
@EnableScheduling
public class ScheduledTasks {
    private static String dir = ClassUtils.getDefaultClassLoader().getResource("").getPath()+"/static/images";
    //每30S执行一次
    /*@Scheduled(fixedRate = 1000 * 30)
    public void reportCurrentTime() throws IOException {
        System.out.println ("Scheduling Tasks Examples: The time is now " +new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format (new Date()));
    }*/
    //每天0点运行
    @Scheduled(cron = "0 0 0 1/1 * ? ")
    public void reportCurrentBy1Day() throws IOException {
        File f = new File(dir + "/gallerys/");
        if (f.exists()) {
            File[] files = f.listFiles();
            if (files.length <= 0) {
                return;
            }
            int rnd = new Random().nextInt(files.length) + 1;
            if (files[rnd].exists()) {
                File desfile = new File(dir + "bannerbg.jpg");
                if (!desfile.exists()) {
                    desfile.createNewFile();
                }
                FileCopyUtils.copy(files[rnd], desfile);
            }
        }
    }
}
